package com.example.weight.wormHandle.cultivate;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.flocculation.xuningshebeijiancha;
import com.example.weight.greenSeasons.waterDeal.EquipmentWeeklyMaintainTable;
import com.example.weight.wormHandle.garbageDisposal.researchDevelopment.BatchGroupNumber;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class ChouJian extends AppCompatActivity {
    private TitleBar titleBar;
    private  int belongTo_id = -1;
    private String factory;

//    private Spinner batchGroupNumber;
    private EditText chou_jian_num;

    //备选批次等列表
    private List<BatchGroupNumber> batchGroupNumberList;

    // choujian_dataList
    private List<choujian_dataItem> choujian_dataList=new ArrayList<>();

    private ChoujianAdapter adapter;

    private TextView date;

    int selectedId = -1;

    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chou_jian);
        Intent previousIntent = getIntent();
        factory = previousIntent.getStringExtra("factory");

        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) { ChouJian.this.finish();}

            @Override
            public void onTitleClick(View v) { }
            @Override
            public void onRightClick(View v) { }
        });

//        batchGroupNumber = findViewById(R.id.select_batch);
//        chou_jian_num = findViewById(R.id.chou_jian_num);

        batchGroupNumberList = new ArrayList<>();
        date = findViewById(R.id.tv_big_out_date);

//        //用LayoutInflater加载布局
//        LayoutInflater factory = LayoutInflater.from(ChouJian.this);
//
//        //获取dialog布局文件获取View
//        final View choujianItemView = factory.inflate(R.layout.activity_choujian_item, null);


        RadioGroup radioGroup;
        RadioButton qualified_button;
        RadioButton disqualified_button;



        //获取可以进行抽检的批次、组别、小虫盒号列表
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/hsmpy/Sampling/getlist?date=" + date.getText() + "&factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                if( data.length()>0){
                                    for (int i=0; i < data.length(); i++){
                                        JSONObject record = data.getJSONObject(i);
                                        Log.d("record",record.toString());
                                        batchGroupNumberList.add(new BatchGroupNumber(record.getInt("id"),record.getString("batch"),record.getString("wormGroup"),record.getString("smallBugBreedBoxNumber"),"",record.optString("bigBugBreedEndTime")));
                                        choujian_dataItem e=new choujian_dataItem(record.get("batch").toString(), record.get("wormGroup").toString(), record.get("tinyBugBreedBoxNumber").toString(),record.get("goWhere").toString(),Integer.parseInt(record.get("id").toString()));
                                        if(i < 3){
                                            choujian_dataList.add(e);
                                            adapter.notifyDataSetChanged();
                                        }
                                    }
                                    Log.d("ChouJianBatchList", batchGroupNumberList.toString());
                                    ArrayAdapter<BatchGroupNumber> adapter = new ArrayAdapter<BatchGroupNumber>(ChouJian.this, android.R.layout.simple_spinner_item,batchGroupNumberList);
//                                    batchGroupNumber.setAdapter(adapter);
//                                    batchGroupNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                                        @Override
//                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                                            belongTo_id = batchGroupNumberList.get(position).id;
//                                            Toast.makeText(ChouJian.this, "抽检小虫盒号："+belongTo_id, Toast.LENGTH_SHORT).show();
//                                        }
//
//                                        @Override
//                                        public void onNothingSelected(AdapterView<?> parent) {
//                                            belongTo_id = -1;
//                                        }
//                                    });
//                                    batchGroupNumber.setSelection(0,true);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(ChouJian.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);

        // 先拿到数据并放在适配器上
        adapter=new ChoujianAdapter(ChouJian.this,R.layout.activity_choujian_item,choujian_dataList);

        // 将适配器上的数据传递给listView
        ListView listView=findViewById(R.id.choujian_list_view);
        listView.setAdapter(adapter);

        // 为ListView注册一个监听器，当用户点击了ListView中的任何一个子项时，就会回调onItemClick()方法
        // 在这个方法中可以通过position参数判断出用户点击的是那一个子项
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RadioGroup radioGroup  = view.findViewById(R.id.group_button);
                RadioButton qualified_button = view.findViewById(R.id.qualified_button);
                RadioButton disqualified_button = view.findViewById(R.id.disqualified_button);

                String result = parent.getItemAtPosition(position).toString();

                Toast.makeText(ChouJian.this, result, Toast.LENGTH_LONG).show();
                selectedId = choujian_dataList.get(position).getDatabaseId();
                String hehao = choujian_dataList.get(position).getMidBugBoxNumber();
                //equip_1
                qualified_button.setOnClickListener(v -> {
                    Log.d("qualified_button", "clicked");
                    if (qualified_button.isChecked()) {
                        saveNormal(String.valueOf(selectedId), hehao, qualified_button, disqualified_button,radioGroup);
                    }
                });
                disqualified_button.setOnClickListener(v -> {
                    if (disqualified_button.isChecked()) {
                        saveAbnormal(String.valueOf(selectedId), hehao, qualified_button, disqualified_button,radioGroup);
                    }
                });
            }
        });

        date.setText(simpleDateFormat.format(new Date()));
        date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(ChouJian.this, 2, date, calendar);
            }
        });
    }


    public void choose(View view) {
        if (belongTo_id == -1) {
            Toast.makeText(this, "请选择批次、组别、小虫盒号", Toast.LENGTH_SHORT).show();
            return;
        }
        if(chou_jian_num.getText().toString().equals("")) {
            Toast.makeText(this, "请填写抽检数量", Toast.LENGTH_SHORT).show();
            return;
        }
        //根据抽检数量获取chou_jian_num条中虫记录
        //提交请求
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/hsmpy/Sampling/sample";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("LB", response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
//                                Log.d("data", data.toString());
                                if( data.length()>0){
                                    choujian_dataList.clear();
                                    for (int i=0; i < data.length(); i++){
                                        JSONObject record = data.getJSONObject(i);
                                        Log.d("record", record.toString());
                                        choujian_dataItem e=new choujian_dataItem(record.get("batch").toString(), record.get("wormGroup").toString(), record.get("tinyBugBreedBoxNumber").toString(),record.get("goWhere").toString(),Integer.parseInt(record.get("id").toString()));
//                                        choujian_dataItem e=new choujian_dataItem("py5",5);
                                        choujian_dataList.add(e);
                                        adapter.notifyDataSetChanged();
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(ChouJian.this, "抽检中虫盒号获取失败", Toast.LENGTH_SHORT).show();
                Log.d("LB", error.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map=new HashMap<>();
                map.put("id", belongTo_id+"");
                map.put("num", chou_jian_num.getText().toString());
                map.put("factory",factory);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);

        adapter.notifyDataSetChanged();
    }

    public void saveNormal(String selectedId, String hehao, RadioButton normal_rb, RadioButton abnormal_rb,RadioGroup rb) {
        new AlertDialog.Builder(this)
                .setTitle("确定 “"+ hehao +"” 正常？")
                .setCancelable(false)
                .setNegativeButton("否", ((dialog, which) -> rb.clearCheck()))
                .setPositiveButton("是", (dialog, which) ->{
                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/hsmpy/Sampling/add";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("zys", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.equals("200")) {
                                            normal_rb.setClickable(false);
                                            abnormal_rb.setClickable(false);
                                            Toast.makeText(ChouJian.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        } else
                                            Toast.makeText(ChouJian.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(ChouJian.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", selectedId);
                            map.put("is_qualified", "是");
                            map.put("inspection_remarks", "合格");
                            map.put("factory",factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    public void saveAbnormal(String selectedId, String hehao, RadioButton normal_rb, RadioButton abnormal_rb,RadioGroup rb) {
        final EditText equipment_problem = new EditText(this);
        equipment_problem.setHint("   输入问题:");
        new AlertDialog.Builder(this)
                .setTitle("请填写 “"+ hehao +"” 异常原因？")
                .setView(equipment_problem)
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) -> rb.clearCheck()))
                .setPositiveButton("提交", (dialog, which) ->{
                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/hsmpy/Sampling/add";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.equals("200")){
                                            normal_rb.setClickable(false);
                                            abnormal_rb.setClickable(false);
                                            Toast.makeText(ChouJian.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        } else
                                            Toast.makeText(ChouJian.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(ChouJian.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", selectedId);
                            map.put("is_qualified", "否");
                            map.put("inspection_remarks", equipment_problem.getText().toString());
                            map.put("factory",factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    public void allDone(String equipment_name){
        new AlertDialog.Builder(this)
                .setTitle(" “"+ equipment_name +"” 未检查，是否退出")
                .setCancelable(false)
                .setNegativeButton("否", ((dialog, which) -> {
                    return;
                }))
                .setPositiveButton("是", (dialog, which) ->{
                    ChouJian.this.finish();
                })
                .show();
    }

    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    //功能相关
    public void saveNormal(String equipment_name, RadioButton normal_rb, RadioButton abnormal_rb,
                           RadioGroup rb, String maintainContent) {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("确定 “"+ equipment_name +"” 正常？")
                .setCancelable(false)
                .setNegativeButton("否", ((dialog, which) ->{
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                    rb.clearCheck();
                }))
                .setPositiveButton("是", (dialog, which) ->{
                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/shlj/sjqWaterProductionEquipmentMaintenanceMaintenance/add_week_recorder";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.equals("200")){
                                            normal_rb.setClickable(false);
                                            abnormal_rb.setClickable(false);
                                            Log.d("sr",jsonObject.toString());
                                            Toast.makeText(ChouJian.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        }
                                        else {
                                            Toast.makeText(ChouJian.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                            normal_rb.setChecked(false);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(ChouJian.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipment_name", equipment_name);
                            map.put("maintenanceContent", maintainContent);
                            map.put("isNormal","正常");
                            map.put("remarks", " ");
                            map.put("factory",factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    public void saveAbnormal(String equipment_name, RadioButton normal_rb, RadioButton abnormal_rb,
                             RadioGroup rb, String maintainContent) {
        final EditText equipment_problem = new EditText(this);
        equipment_problem.setHint("   输入问题:");
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("请填写 “"+ equipment_name +"” 异常原因？")
                .setView(equipment_problem)
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->{
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                    rb.clearCheck();
                }
                ))
                .setPositiveButton("提交", (dialog, which) ->{
                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/shlj/sjqWaterProductionEquipmentMaintenanceMaintenance/add_week_recorder";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.equals("200")){
                                            normal_rb.setClickable(false);
                                            abnormal_rb.setClickable(false);
                                            Log.d("sr",jsonObject.toString());
                                            Toast.makeText(ChouJian.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        }
                                        else {
                                            Toast.makeText(ChouJian.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                            abnormal_rb.setChecked(false);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(ChouJian.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipment_name", equipment_name);
                            map.put("maintenanceContent", maintainContent);
                            map.put("isNormal","异常");
                            map.put("remarks", equipment_problem.getText().toString());
                            map.put("factory",factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
}